<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Utils\ModelOperatorTrait;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    use ModelOperatorTrait;

    protected function model(){
        return app(\App\Models\User::class);
    }

    protected function getAttributes(){
        return [
            'username' => '用户名',
            'nickname' => '昵称',
            'password' => '密码',
            'role_ids' => '角色组',
            'role_ids.*' => '角色编号'
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return formatJsonResponse($this->pageModel(request()->input()));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = [
            'username' => 'required|unique:users,username',
            'nickname' => 'required',
            'password' => 'required|string|min:6|confirmed',
            'roleIds' => [
                'required',
                'array'
            ],
            'roleIds.*' => 'required|exists:roles,id'
        ];

        $this->validate($rules);

        try {
            \DB::beginTransaction();

            $data = [
                'username' => $request->username,
                'nickname' => $request->nickname,
                'password' => bcrypt($request->password),
            ];

            $user = $this->storeModel($data);

            foreach ($request->roleIds as $roleId) {
                $this->storeModel(['role_id' => $roleId,'user_id'=>$user->id],app(\App\Models\UserRole::class));
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();

            throw new \Exception($e->getMessage(),10003);
        }

        return formatJsonResponse();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return formatJsonResponse($this->findModel($id,['roles']));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $rules = [
            'username' => [
                'required',
                 Rule::unique('users','username')->where(function ($query) use ($id){
                    $query->where('id','<>', $id);
                })
            ],
            'nickname' => 'required',
            'roleIds' => [
                'required',
                'array'
            ],
            'roleIds.*' => 'required|exists:roles,id'
        ];

        if(isset($request->password)){
            $rules['password'] = 'required|string|min:6|confirmed';
        }

        $this->validate($rules);

        try {
            \DB::beginTransaction();

            $data = [
                'username' => $request->username,
                'nickname' => $request->nickname,
            ];

            if(isset($request->password)){
                $data['password'] = bcrypt($request->password);
            }

            $this->updateModel($id,$data);

            $this->dropModel(['user_id' => $id],app(\App\Models\UserRole::class));

            foreach ($request->roleIds as $roleId) {
                $this->storeModel(['role_id' => $roleId,'user_id'=> $id],app(\App\Models\UserRole::class));
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback();

            throw new \Exception($e->getMessage(),10003);
        }

        



        return formatJsonResponse();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->deleteModel($id);

        return formatJsonResponse();
    }


    public function roleId(){
        return formatJsonResponse(itemOption($this->model()::$ROLE_ID));
    }
}
